package server

import (
	"context"
	"fmt"
	"gin-init/configs"
	"gin-init/pkg/logger"
	"net/http"
	"time"

	"github.com/robfig/cron"
)

func RunServer(ctx context.Context) (server *http.Server, scheduled *cron.Cron, err error) {
	injector, err := BuildInjector(ctx)
	if err != nil {
		return nil, nil, err
	}

	server = &http.Server{
		Addr:           fmt.Sprintf(":%d", configs.ProjectPort),
		Handler:        injector.Engine,
		ReadTimeout:    60 * time.Second,
		WriteTimeout:   60 * time.Second,
		IdleTimeout:    60 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	go func() {
		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Panicw("http server startup err", "err", err)
		}
	}()

	//判断是否开启定时任务
	if configs.Get().Timing.Open {
		//创建定时任务控制器
		scheduled = cron.New()
		//启动定时任务
		scheduled.Start()
	}
	return
}
